import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Row, Col } from 'antd';
import MainLayout from '../../../components/MainLayout';
import PageHeader from './components/PageHeader';
import NetworkInfoSection from './components/NetworkInfoSection';
import RulesSection from './components/RulesSection';
import MembersSection from './components/MembersSection';
import NonMemberPrompt from './components/NonMemberPrompt';
import LoadingView from './components/LoadingView';
import ErrorView from './components/ErrorView';
import networkService from '../../../services/network';
import './NetworkDetail.css';
import Toast from '../../../components/Toast';

const NetworkDetail = () => {
  const { networkId } = useParams();
  const navigate = useNavigate();
  
  // 状态管理
  const [network, setNetwork] = useState(null);
  const [userRole, setUserRole] = useState(null);
  const [members, setMembers] = useState([]);
  const [rules, setRules] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [membersLoading, setMembersLoading] = useState(false);
  const [operationLoading, setOperationLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 获取网络数据
  const fetchNetworkData = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      // 并行请求网络详情和用户角色
      const [networkDetail, roleInfo] = await Promise.all([
        networkService.getNetworkDetail(networkId),
        networkService.getUserNetworkRole(networkId).catch(() => ({ data: { code: 404 } }))
      ]);

      if (networkDetail.data.code === 200) {
        setNetwork(networkDetail.data.data);
      } else {
        setError('获取网络信息失败');
        return;
      }

      if (roleInfo.data.code === 200) {
        setUserRole(roleInfo.data.data.role);
        // 如果是成员，获取成员列表和规则
        await fetchMembersAndRules(roleInfo.data.data.role);
      } else {
        // 用户不是成员，清空角色状态
        setUserRole(null);
        setMembers([]);
        setRules(null);
      }
    } catch (err) {
      setError(err.response?.data?.message || '获取网络信息失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 获取成员和规则数据
  const fetchMembersAndRules = async (role = userRole) => {
    try {
      setMembersLoading(true);
      const [membersResponse, rulesResponse] = await Promise.all([
        networkService.getNetworkMembers(networkId),
        role === 'admin' ? 
          networkService.getNetworkRules(networkId) : 
          Promise.resolve({ data: { code: 404 } })
      ]);

      if (membersResponse.data.code === 200) {
        setMembers(membersResponse.data.data || []);
      }

      if (rulesResponse.data.code === 200) {
        setRules(rulesResponse.data.data);
      }
    } catch (err) {
    } finally {
      setMembersLoading(false);
    }
  };

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  // 刷新数据的函数
  const handleRefresh = async () => {
    await fetchNetworkData();
  };

  // 加入网络
  const handleJoinNetwork = async () => {
    try {
      setOperationLoading(true);
      const response = await networkService.joinNetwork(networkId);
      
      if (response.data.code === 200) {
        showToastMessage('成功加入局域网');
        
        // 重新获取完整的网络数据以确保状态同步
        await fetchNetworkData();
      } else {
        showToastMessage(response.data.message || '加入失败，请稍后重试');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '加入失败，请稍后重试');
    } finally {
      setOperationLoading(false);
    }
  };

  // 离开网络
  const handleLeaveNetwork = async () => {
    try {
      setOperationLoading(true);
      const response = await networkService.leaveNetwork(networkId);
      
      if (response.data.code === 200) {
        showToastMessage('成功退出局域网');
        setTimeout(() => {
          navigate('/network');
        }, 1500);
      } else {
        showToastMessage(response.data.message || '退出失败，请稍后重试');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '退出失败，请稍后重试');
    } finally {
      setOperationLoading(false);
    }
  };

  // 修改成员角色
  const handleUpdateMemberRole = async (userId, newRole, username) => {
    try {
      setOperationLoading(true);
      const response = await networkService.updateMemberRole(networkId, userId, newRole);
      if (response.data.code === 200) {
        showToastMessage(`成功将 ${username} 设为${newRole === 'admin' ? '管理员' : '普通成员'}`);
        
        // 更新成员列表
        setMembers(prevMembers => 
          prevMembers.map(member => 
            member.userId === userId ? { ...member, role: newRole } : member
          )
        );
        
        // 检查是否是当前用户降级自己
        const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
        if (userId === currentUser.userId && newRole === 'member') {
          // 当前用户降级自己，更新用户角色并重新获取数据
          setUserRole('member');
          setRules(null); // 清空规则数据，因为普通成员无权查看
          // 重新获取成员和规则数据（普通成员看不到规则）
          await fetchMembersAndRules('member');
        }
      } else {
        showToastMessage(response.data.message || '角色修改失败');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '角色修改失败，请稍后重试');
    } finally {
      setOperationLoading(false);
    }
  };

  // 移除成员
  const handleRemoveMember = async (userId, username, banDuration) => {
    try {
      setOperationLoading(true);
      const response = await networkService.removeMember(networkId, userId, banDuration);
      
      if (response.data.code === 200) {
        showToastMessage(`成功移除 ${username}${banDuration > 0 ? `，并禁止其在 ${banDuration} 小时内重新加入` : ''}`);
        // 从成员列表中移除该成员
        setMembers(prevMembers => prevMembers.filter(member => member.userId !== userId));
        // 更新网络成员数量
        if (network) {
          setNetwork(prev => ({ ...prev, memberCount: prev.memberCount - 1 }));
        }
      } else {
        showToastMessage(response.data.message || '移除失败');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '移除失败，请稍后重试');
    } finally {
      setOperationLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchNetworkData();
  }, [networkId]);

  // 加载状态
  if (isLoading) {
    return (
      <MainLayout>
        <LoadingView />
      </MainLayout>
    );
  }

  // 错误状态
  if (error || !network) {
    return (
      <MainLayout>
        <ErrorView 
          error={error || '未找到网络信息'} 
          onBack={() => navigate('/network')}
        />
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      <div className="network-detail-container">
        <div className="network-detail-content">
          {/* 页面头部 */}
          <PageHeader
            network={network}
            userRole={userRole}
            operationLoading={operationLoading}
            onJoinNetwork={handleJoinNetwork}
            onLeaveNetwork={handleLeaveNetwork}
            onManageNetwork={() => navigate(`/network/${networkId}/manage`)}
            onRefresh={handleRefresh}
            refreshLoading={isLoading}
          />

          {/* 网络信息和规则 */}
          <div className="info-sections">
            <Row gutter={[24, 24]}>
              <Col xs={24} lg={userRole === 'admin' && rules ? 12 : 24}>
                <NetworkInfoSection network={network} userRole={userRole} />
              </Col>
              {userRole === 'admin' && rules && (
                <Col xs={24} lg={12}>
                  <RulesSection 
                    rules={rules} 
                    onEditRules={() => navigate(`/network/${networkId}/manage`)}
                  />
                </Col>
              )}
            </Row>
          </div>

          {/* 成员列表或非成员提示 */}
          {userRole ? (
            <MembersSection
              members={members}
              userRole={userRole}
              isLoading={membersLoading}
              operationLoading={operationLoading}
              onRefresh={fetchMembersAndRules}
              onUpdateMemberRole={handleUpdateMemberRole}
              onRemoveMember={handleRemoveMember}
            />
          ) : (
            <NonMemberPrompt
              network={network}
              operationLoading={operationLoading}
              onJoinNetwork={handleJoinNetwork}
            />
          )}
        </div>
      </div>
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </MainLayout>
  );
};

export default NetworkDetail;